
// 电影相关功能
document.addEventListener('DOMContentLoaded', function () {
    // 加载电影列表
    let maxPage= 1
        loadMovies().then( (value) => {
        maxPage = value;
    });
    loadRankings();

    // 电影筛选功能
    const genreFilter = document.getElementById('genre-filter');
    const regionFilter = document.getElementById('region-filter');
    const sortFilter = document.getElementById('sort-filter');

    if (genreFilter && regionFilter && sortFilter) {
        [genreFilter, regionFilter, sortFilter].forEach(filter => {
            filter.addEventListener('change', function () {
                loadMovies();
            });
        });
    }

    // 分页功能
    const prevPageBtn = document.getElementById('prev-page');
    const nextPageBtn = document.getElementById('next-page');
    const pageInfo = document.getElementById('page-info');

    if (prevPageBtn && nextPageBtn && pageInfo) {
        let currentPage = 1;
        const pageSize = 10; // 每页显示的电影数量

        prevPageBtn.addEventListener('click', function () {
            if (currentPage > 1) {
                currentPage--;
                loadMovies(currentPage, pageSize);
                updatePageInfo();
            }
        });

        nextPageBtn.addEventListener('click', function () {
            if (currentPage >= maxPage) {
                return;
            }
            currentPage++;
            loadMovies(currentPage, pageSize);
            updatePageInfo();
        });

        function updatePageInfo() {
            pageInfo.textContent = `第${currentPage}页`;
        }
    }
});

// 加载电影列表
async function loadMovies(page = 1,pageSize = 10) {
    const genre = document.getElementById('genre-filter').value;
    const region = document.getElementById('region-filter').value;
    const sort = document.getElementById('sort-filter').value;
    console.log(genre, region, sort);
    let maxPage=0;
    try {
        const movies = await getMovies(genre, region, sort);
        maxPage=movies.length/pageSize;
        const moviesOnPage = movies.slice((page - 1) * pageSize, page * pageSize);
        renderMovies(moviesOnPage);
    } catch (error) {
        console.error('加载电影列表错误:', error);
        alert('加载电影列表失败');
    }
    return maxPage;
}

// 渲染电影列表
function renderMovies(movies) {
    const movieGrid = document.getElementById('movie-grid');
    if (!movieGrid) return;

    if (movies.length === 0) {
        movieGrid.innerHTML = '<p class="no-results">没有找到匹配的电影</p>';
        return;
    }

    movieGrid.innerHTML = movies.map(movie => `
        <div class="movie-card" onclick="window.location.href='/movie/detail?id=${movie.id}'">
            <div class="movie-poster">
                <img src="/image/${movie.coverUrl}" alt="${movie.title}海报">
                <div class="movie-vip-badge ${movie.vip ? 'vip' : 'free'}">${movie.vip ? 'VIP' : '免费'}</div>
            </div>
            <div class="movie-info">
                <h3 class="movie-title">${movie.title}</h3>
                <div class="movie-meta">
                    <span><i class="fas fa-star"></i> ${movie.rating}</span>
                    <span><i class="fas fa-calendar"></i> ${movie.releaseDate.substring(0, 4)}</span>
                </div>
            </div>
        </div>
    `).join('');
}

// 加载排行榜
async function loadRankings() {
    const tabIds = ['weekly', 'monthly', 'all-time', 'top-rated'];

    for (const tabId of tabIds) {
        try {
            const rankings = await mockGetRankings(tabId);

            renderRankings(tabId, rankings);
        } catch (error) {
            console.error(`加载${tabId}排行榜错误:`, error);
        }
    }
}

// 渲染排行榜
function renderRankings(tabId, rankings) {
    const rankingContainer = document.getElementById(`${tabId}-ranking`);
    if (!rankingContainer) return;

    if (rankings.length === 0) {
        rankingContainer.innerHTML = '<p>暂无排行榜数据</p>';
        return;
    }

    rankingContainer.innerHTML = rankings.map((movie, index) => `
        <div class="ranking-item ${index < 3 ? 'top-' + (index + 1) : ''}">
            <div class="ranking-number">${index + 1}</div>
            <div class="ranking-poster">
                <img src="${'image/'+movie.poster || 'assets/images/default-poster.jpg'}" alt="${movie.title}海报">
            </div>
            <div class="ranking-info">
                <h3 class="ranking-title">${movie.title}</h3>
                <div class="ranking-meta">
                    <span><i class="fas fa-star"></i> ${movie.rating}</span>
                    <span><i class="fas fa-calendar"></i> ${movie.year}</span>
                </div>
            </div>
        </div>
    `).join('');
}

// 模拟获取电影函数
async function getMovies(genre, region, sort) {
    let movies;
    console.log("getMovies");
    await $.get("/movie/getAllMovies", function (data) {
        movies = data;
    });

    // 简单的筛选逻辑
    let filteredMovies = [...movies];

    if (genre !== 'all') {
        filteredMovies = filteredMovies.filter(movie => movie.type.includes(genre));
    }

    if (region !== 'all') {
        filteredMovies = filteredMovies.filter(movie => movie.region === region);
    }

    // 简单的排序逻辑
    switch (sort) {
        case 'popularity':
            // 这里应该是按热度排序，示例中简单按rating排序
            filteredMovies.sort((a, b) => b.rating - a.rating);
            break;
        case 'rating':
            filteredMovies.sort((a, b) => b.rating - a.rating);
            break;
        case 'date':
            filteredMovies.sort((a, b) => b.year - a.year);
            break;
    }

    return filteredMovies;
}

async function mockGetRankings(type) {

    let mockRankings = [];
    let response;
    switch (type) {
        case 'weekly':
            // 本周排行
            response = await axios.get("/ranking/getWeeklyRankings");
            mockRankings = response.data;
            console.log(mockRankings);
            break;
        case 'monthly':
            // 本月排行
            response = await axios.get("/ranking/getMonthlyRankings");
            mockRankings = response.data;
            console.log(mockRankings);
            break;
        case 'all-time':
            // 全部排行
            response = await axios.get("/ranking/getAllTimeRankings");
            mockRankings = response.data;
            console.log(mockRankings);
            break;
        case 'top-rated':
            // 好评排行
            response = await axios.get("/ranking/getTopRatedRankings");
            mockRankings = response.data;
            console.log(mockRankings);
            break;
    }
    switch (type) {
        case 'weekly':
            // 本周排行 - 返回前5
            return mockRankings.slice(0, 5);
        case 'monthly':
            // 本月排行 - 返回前5
            return mockRankings.slice(0, 5);
        case 'all-time':
            // 全部排行 - 返回前10
            return mockRankings.slice(0, 10);
        case 'top-rated':
            // 好评排行 - 按rating排序
            return [...mockRankings].sort((a, b) => b.rating - a.rating).slice(0, 10);
        default:
            return mockRankings.slice(0, 5);
    }
}
$(document).ready(function() {
    const commentForm = $('#commentForm');
    const charCount = commentForm.find('.char-count span');
    const textarea = commentForm.find('textarea');
    const submitBtn = commentForm.find('button[type="submit"]');

    // 实时字数统计
    textarea.on('input', function() {
    const length = $(this).val().length;
    charCount.text(500 - length);
    submitBtn.prop('disabled', length < 5);
});

    // 表单提交处理
    commentForm.submit(function(e) {
    e.preventDefault();
    submitBtn.prop('disabled', true).text('发布中...');

    $.ajax({
    url: '/api/comments',
    method: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({
    movieId: commentForm.find('input[name="movieId"]').val(),
    content: textarea.val().trim()
}),
    success: function(res) {
    if (res.code === 200) {
    // 清空表单
    textarea.val('');
    charCount.text('500');

    // 刷新评论列表
    loadComments();
} else {
    showError(res.message || '评论发布失败');
}
},
    error: function(xhr) {
    if (xhr.status === 401) {
    window.location.href = '/user/login?returnUrl=' + encodeURIComponent(window.location.href);
} else {
    showError('请求失败，请稍后再试');
}
},
    complete: function() {
    submitBtn.prop('disabled', false).text('发布评论');
}
});
});

function loadComments() {
    $.get('/api/comments', {movieId: commentForm.find('input[name="movieId"]').val()}, function(res) {
    if (res.code === 200) {
    const commentsContainer = $('#reviews .comments-container');
    commentsContainer.empty();

    if (res.data.length === 0) {
    commentsContainer.html(`
                        <div class="no-comments">
                            <i class="fas fa-comment-slash"></i>
                            <p>暂无评论，快来发表第一篇观影感受吧！</p>
                        </div>
                    `);
    return;
}

    res.data.forEach(comment => {
    commentsContainer.append(`
                        <div class="comment-item">
                            <div class="comment-header">
                                <span class="user-id">用户 ${comment.userId}</span>
                                <span class="comment-time">${new Date(comment.createdDate).toLocaleString()}</span>
                            </div>
                            <div class="comment-content">${comment.content}</div>
                        </div>
                    `);
});

    // 更新评论计数
    $('#reviews .comment-count').text(res.data.length + ' 条');
}
});
}

    // 错误提示函数
    function showError(message) {
    alert(message);
}
});